import React, { useState, useEffect } from "react";
import { Page, useNavigate, useLocation } from "zmp-ui";
import { useI18n } from "../i18n";
import Navbar from "../components/navbar";
import { getDeviceDetail } from "../api/endpoints";
import { DeviceInfo } from "../api/types";

const ScanResultPage: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const location = useLocation();
  
  const [scanResult, setScanResult] = useState<string>("");
  const [deviceInfo, setDeviceInfo] = useState<DeviceInfo | null>(null);
  const [isValidating, setIsValidating] = useState(false);
  const [validationError, setValidationError] = useState<string>("");

  useEffect(() => {
    // 从路由状态中获取扫码结果
    const result = location.state?.scanResult;
    if (result) {
      setScanResult(result);
      processScanResult(result);
    } else {
      // 如果没有扫码结果，返回扫码页面
      navigate('/scan');
    }
  }, [location.state, navigate]);

  // 处理扫码结果
  const processScanResult = async (result: string) => {
    try {
      setIsValidating(true);
      setValidationError("");
      
      // 直接使用传递过来的参数作为设备ID
      const deviceId = result;
      
      if (!deviceId) {
        setValidationError(t('scan.deviceIdEmpty'));
        return;
      }
      
      // 直接调用设备详情接口
      const deviceResponse: any = await getDeviceDetail(deviceId);
      
      if (deviceResponse && deviceResponse.rentbox) {
        const rentbox = deviceResponse.rentbox;
        const config = deviceResponse.config;
        const fastConfig = deviceResponse.fastConfig;
        const userCoupons = deviceResponse.userCoupons || [];
        const ADList = deviceResponse.ADList || [];
        
        // 根据powerBankType选择对应的配置
        const currentConfig = config?.powerBankType === 'fast' ? fastConfig : config;
        
        // 将接口返回的数据转换为DeviceInfo格式
        const deviceInfo: DeviceInfo = {
          id: rentbox.id.toString(),
          name: `设备${rentbox.id}`,
          location: rentbox.place || rentbox.location || '未知位置',
          lat: 10.762622, // 默认坐标，实际应该从接口获取
          lng: 106.660172, // 默认坐标，实际应该从接口获取
          status: rentbox.online ? 'available' : 'busy',
          availableCount: 5, // 默认值，实际应该从接口获取
          totalCount: 8, // 默认值，实际应该从接口获取
          powerbankType: config?.powerBankType === 'fast' ? 2 : 1,
          openTime: '24/7', // 默认值，实际应该从接口获取
          // 新增字段存储原始数据
          originalData: {
            rentbox,
            config: currentConfig,
            userCoupons,
            ADList,
            mob: deviceResponse.mob,
            type: deviceResponse.type,
            discountTime: deviceResponse.discountTime
          }
        };
        
        setDeviceInfo(deviceInfo);
      } else {
        setValidationError(t('scan.deviceInfoFailed'));
      }
    } catch (error: any) {
      console.error('获取设备详情失败:', error);
      
      // 检查是否是设备离线错误
      if (error.code === 485) {
        try {
          const errorData = JSON.parse(error.data);
          const deviceSN = errorData.text1?.replace('tủ SN:', '') || t('scan.unknown');
          setValidationError(t('scan.deviceOffline').replace('{{sn}}', deviceSN));
        } catch (parseError) {
          setValidationError(t('scan.deviceOfflineGeneric'));
        }
      } else if (error.msg) {
        // 显示接口返回的错误信息
        setValidationError(error.msg);
      } else {
        // 网络或其他错误
        setValidationError(t('scan.networkError'));
      }
    } finally {
      setIsValidating(false);
    }
  };


  // 确认租借处理 - 跳转到创建订单页面
  const handleConfirmRental = (device: DeviceInfo) => {
    // 跳转到创建订单页面，传递设备信息
    navigate('/create-order', { 
      state: { 
        deviceInfo: device,
        scanResult: scanResult
      } 
    });
  };

  const handleBackToScan = () => {
    navigate('/scan');
  };

  return (
    <Page className="page" style={{ backgroundColor: '#F5F5F7', padding: 0 }}>
      {/* 顶部导航栏 */}
      <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
        <Navbar title={t('scan.result')} />
      </div>

      {/* 顶部背景图片区域 */}
      <div style={{
        position: 'relative',
        height: '300px',
        backgroundImage: 'url(/src/assets/img/64217baca49f7eb9b7e7abc1f8c1dae6.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}>
        {/* 左上角文字 */}
        <div style={{
          position: 'absolute',
          top: '20px',
          left: '20px',
          color: 'white',
          fontSize: '14px',
          fontWeight: 'bold'
        }}>
        </div>

        {/* 右上角机柜SN */}
        {deviceInfo && (
          <div style={{
            position: 'absolute',
            top: '20px',
            right: '20px',
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            color: 'white',
            padding: '8px 12px',
            borderRadius: '4px',
            fontSize: '12px',
            fontWeight: 'bold'
          }}>
            {t('scan.cabinetSN')}{deviceInfo.id}
          </div>
        )}
      </div>

      {/* 内容区域 */}
      <div style={{ padding: '20px', paddingBottom: '120px' }}>
        {/* 验证状态 */}
        {isValidating && (
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '12px',
            padding: '20px',
            marginBottom: '20px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            textAlign: 'center'
          }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>⏳</div>
            <div style={{ fontSize: '16px', color: '#666' }}>
              {t('scan.validating')}
            </div>
          </div>
        )}

        {/* 验证错误 */}
        {validationError && (
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '12px',
            padding: '20px',
            marginBottom: '20px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            textAlign: 'center'
          }}>
            {/* <div style={{ fontSize: '48px', marginBottom: '16px' }}>❌</div> */}
            <div style={{ fontSize: '16px', color: '#FF6B6B', marginBottom: '16px' }}>
              {validationError}
            </div>
            <button
              onClick={handleBackToScan}
              style={{
                backgroundColor: '#FF6B35',
                color: '#fff',
                border: 'none',
                borderRadius: '8px',
                padding: '12px 24px',
                fontSize: '14px',
                fontWeight: 'bold',
                cursor: 'pointer'
              }}
            >
              {t('scan.rescan')}
            </button>
          </div>
        )}

        {/* 设备信息卡片 */}
        {deviceInfo && (
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '12px',
            padding: '20px',
            marginBottom: '20px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            {/* 标题 */}
            {/* <div style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '16px',
              textAlign: 'center'
            }}>
              YOUDIAN STAR HƯỚNG DẪN SỬ DỤNG
            </div> */}

            {/* 适配接口 */}
            <div style={{
              fontSize: '14px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '12px'
            }}>
              {t('scan.compatibleInterfaces')}:
            </div>
            
            <div style={{
              display: 'flex',
              justifyContent: 'space-around',
              marginBottom: '20px'
            }}>
              <div style={{ textAlign: 'center' }}>
                <div style={{
                  width: '40px',
                  height: '40px',
                  backgroundColor: '#f0f0f0',
                  borderRadius: '8px',
                  margin: '0 auto 8px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '20px'
                }}>
                  📱
                </div>
                <div style={{ fontSize: '12px', color: '#666' }}>iOS</div>
                <div style={{
                  width: '20px',
                  height: '12px',
                  backgroundColor: '#4CAF50',
                  borderRadius: '6px',
                  margin: '4px auto 0',
                  position: 'relative'
                }}>
                  <div style={{
                    width: '8px',
                    height: '8px',
                    backgroundColor: '#fff',
                    borderRadius: '50%',
                    position: 'absolute',
                    top: '2px',
                    right: '2px'
                  }}></div>
                </div>
              </div>
              
              <div style={{ textAlign: 'center' }}>
                <div style={{
                  width: '40px',
                  height: '40px',
                  backgroundColor: '#f0f0f0',
                  borderRadius: '8px',
                  margin: '0 auto 8px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '20px'
                }}>
                  🔌
                </div>
                <div style={{ fontSize: '12px', color: '#666' }}>Type C</div>
                <div style={{
                  width: '20px',
                  height: '12px',
                  backgroundColor: '#4CAF50',
                  borderRadius: '6px',
                  margin: '4px auto 0',
                  position: 'relative'
                }}>
                  <div style={{
                    width: '8px',
                    height: '8px',
                    backgroundColor: '#fff',
                    borderRadius: '50%',
                    position: 'absolute',
                    top: '2px',
                    right: '2px'
                  }}></div>
                </div>
              </div>
              
              <div style={{ textAlign: 'center' }}>
                <div style={{
                  width: '40px',
                  height: '40px',
                  backgroundColor: '#f0f0f0',
                  borderRadius: '8px',
                  margin: '0 auto 8px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '20px'
                }}>
                  🔌
                </div>
                <div style={{ fontSize: '12px', color: '#666' }}>Android</div>
                <div style={{
                  width: '20px',
                  height: '12px',
                  backgroundColor: '#4CAF50',
                  borderRadius: '6px',
                  margin: '4px auto 0',
                  position: 'relative'
                }}>
                  <div style={{
                    width: '8px',
                    height: '8px',
                    backgroundColor: '#fff',
                    borderRadius: '50%',
                    position: 'absolute',
                    top: '2px',
                    right: '2px'
                  }}></div>
                </div>
              </div>
            </div>

            {/* 计费规则 */}
            <div style={{
              fontSize: '14px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '12px'
            }}>
              {t('scan.billingRules')}:
            </div>
            
            <div style={{ fontSize: '12px', color: '#666', lineHeight: '1.6' }}>
              {deviceInfo.originalData?.config ? (
                <>
                  <div>• {t('scan.freeMinutes').replace('{{minutes}}', deviceInfo.originalData.config.minuteFree || 5)}.</div>
                  <div>• {t('scan.firstMinuteFee').replace('{{fee}}', deviceInfo.originalData.config.fistMinuteFee || 0)}.</div>
                  <div>• {t('scan.cycleFee').replace('{{fee}}', deviceInfo.originalData.config.cycleFee || 1).replace('{{cycle}}', deviceInfo.originalData.config.minuteCycle || 30)}.</div>
                  <div>• {t('scan.dayFee').replace('{{fee}}', deviceInfo.originalData.config.dayFee || 30)}.</div>
                  <div>• {t('scan.securityFee').replace('{{fee}}', deviceInfo.originalData.config.securityFee || 99)}</div>
                  {deviceInfo.originalData.config.securityFree && (
                    <div>• {t('scan.firstTimeFree')}</div>
                  )}
                </>
              ) : (
                <>
                  <div>• {t('scan.defaultFreeMinutes')}.</div>
                  <div>• {t('scan.defaultHourlyFee')}.</div>
                  <div>• {t('scan.defaultDailyFee')}.</div>
                  <div>• {t('scan.defaultExtendedFee')}.</div>
                </>
              )}
            </div>
          </div>
        )}

        {/* 用户优惠券 */}
        {/* {deviceInfo?.originalData?.userCoupons && deviceInfo.originalData.userCoupons.length > 0 && (
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '12px',
            padding: '20px',
            marginBottom: '20px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{
              fontSize: '14px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '12px'
            }}>
              可用优惠券:
            </div>
            
            {deviceInfo.originalData.userCoupons.map((coupon: any, index: number) => (
              <div key={index} style={{
                backgroundColor: '#FFF3E0',
                border: '1px solid #FFB74D',
                borderRadius: '8px',
                padding: '12px',
                marginBottom: '8px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 'bold', color: '#E65100' }}>
                    {coupon.name}
                  </div>
                  <div style={{ fontSize: '10px', color: '#666', marginTop: '2px' }}>
                    {coupon.type === 1 ? `减免${coupon.discount}₫` : `折扣${coupon.discount}%`}
                  </div>
                </div>
                <div style={{
                  fontSize: '10px',
                  color: '#666',
                  textAlign: 'right'
                }}>
                  <div>有效期至:</div>
                  <div>{coupon.expireTime}</div>
                </div>
              </div>
            ))}
          </div>
        )} */}

        {/* 广告信息 */}
        {/* {deviceInfo?.originalData?.ADList && deviceInfo.originalData.ADList.length > 0 && (
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '12px',
            padding: '20px',
            marginBottom: '20px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{
              fontSize: '14px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '12px'
            }}>
              推荐信息:
            </div>
            
            {deviceInfo.originalData.ADList.map((ad: any, index: number) => (
              <div key={index} style={{
                backgroundColor: '#F8F9FA',
                border: '1px solid #E9ECEF',
                borderRadius: '8px',
                padding: '12px',
                marginBottom: '8px',
                cursor: 'pointer'
              }}
              onClick={() => {
                if (ad.forward) {
                  window.open(ad.forward, '_blank');
                }
              }}>
                <div style={{ fontSize: '12px', fontWeight: 'bold', color: '#333', marginBottom: '4px' }}>
                  {ad.title}
                </div>
                {ad.url1 && (
                  <div style={{
                    width: '100%',
                    height: '120px',
                    backgroundImage: `url(${ad.url1})`,
                    backgroundSize: 'cover',
                    backgroundPosition: 'center',
                    borderRadius: '4px',
                    marginBottom: '8px'
                  }}></div>
                )}
              </div>
            ))}
          </div>
        )} */}

        {/* 底部确认按钮 */}
        {deviceInfo && (
          <div style={{
            position: 'fixed',
            bottom: '0',
            left: '0',
            right: '0',
            padding: '20px',
            backgroundColor: '#fff',
            borderTop: '1px solid #eee',
            zIndex: 1000
          }}>
            <button
              onClick={() => handleConfirmRental(deviceInfo)}
              disabled={deviceInfo.status !== 'available' || deviceInfo.availableCount === 0}
              style={{
                width: '100%',
                height: '50px',
                backgroundColor: deviceInfo.status === 'available' && deviceInfo.availableCount > 0
                  ? '#FF6B35' : '#ccc',
                color: '#fff',
                border: 'none',
                borderRadius: '25px',
                fontSize: '16px',
                fontWeight: 'bold',
                cursor: deviceInfo.status === 'available' && deviceInfo.availableCount > 0
                  ? 'pointer' : 'not-allowed',
                transition: 'all 0.2s'
              }}
            >
              {deviceInfo.status === 'available' && deviceInfo.availableCount > 0 
                 ? t('scan.confirmRental') : t('scan.unavailable')}
            </button>
          </div>
        )}
      </div>
    </Page>
  );
};

export default ScanResultPage;
